package com.atlin;

import lombok.extern.slf4j.Slf4j;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import static com.atlin.util.ByteBufferUtil.debugAll;

@Slf4j
public class ChannelDemo1 {
    public static void main(String[] args) {

/*        try (RandomAccessFile file = new RandomAccessFile("demoData/data.txt", "rw")) {
            FileChannel channel = file.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(10);
            do {
                //向buff写入数据
                int len = channel.read(buffer);
                log.debug("读到字节数{}", len);
                if (len == -1) {
                    break;
                }
                // 切换 buff 到读模式
                buffer.flip();
                while (buffer.hasRemaining()) {
                    log.debug("{}", (char) buffer.get());
                }
                //切换 buff 到写模式
                buffer.clear();
            } while (true);

        } catch (Exception e) {
            e.printStackTrace();
        }*/

        try (RandomAccessFile file = new RandomAccessFile("demoData/data.txt", "rw")) {
            FileChannel channel = file.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(10);
            do {
                int len = channel.read(buffer);
                log.debug("读到{}字节", len);
                if (len == -1) {
                    break;
                }
                buffer.flip();
//                while (buffer.hasRemaining()) {
//                    log.debug("{}", (char) buffer.get());
//                }
                int i = 3;
                while (--i >= 0) {
                    log.debug("{}", (char) buffer.get());
                }
                buffer.compact();

            } while (true);

            buffer.flip();
            debugAll(buffer);
            while (buffer.hasRemaining()) {
                log.debug("{}", (char) buffer.get());
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
} 
